package com.me.chat.service.impl.user;

import com.alibaba.fastjson.JSON;
import com.me.chat.mapper.relation.SingleRelationReqMapper;
import com.me.chat.mapper.user.UserMapper;
import com.me.chat.pojo.relation.qo.SingleRelationReqQO;
import com.me.chat.pojo.user.UserInfo;
import com.me.chat.pojo.user.qo.UserInfoQO;
import com.me.chat.pojo.user.vo.UserDetailInfoVO;
import com.me.chat.service.user.UserService;
import com.me.chat.util.CommonUtil;
import com.me.chat.util.RedisKey;
import com.me.chat.util.SimpleUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author VULCAN
 * @create 2020/2/17 20:08
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    SingleRelationReqMapper singleRelationReqMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    PasswordEncoder passwordEncoder;



    /**
     * 获得用户信息，有缓存 无需userId 直接从token中获取
     */
    @Override
    public UserInfo getUserInfo() {
        String userId = SimpleUserInfo.getUserId();
        UserInfo userInfo = this.getUserInfo(userId);
        return userInfo;
    }

    @Override
    public UserInfo getUserInfo(String userId) {
        //redis 中的用户信息的key  这个用户用一次，缓存就会更新一次
        final String key = RedisKey.userInfoKey(userId);
        //带有缓存的获取用户信息
        UserInfo userInfo = this.getUserInfoNoSetCatch(userId);
        //把查出来当userInfo 转化为json 存入redis
        String userInfoJson = JSON.toJSONString(userInfo);
        //设置一天过期时间
        stringRedisTemplate.opsForValue().set(key,userInfoJson,1, TimeUnit.DAYS);
        return userInfo;
    }

    @Override
    public UserInfo getUserInfoNoSetCatch(String userId) {
        //redis 中的用户信息的key
        final String key = RedisKey.userInfoKey(userId);
        String userInfoFromRedis = stringRedisTemplate.opsForValue().get(key);
        UserInfo userInfo = null;

        //如果redis中存在这个userInfo
        if(userInfoFromRedis!= null && !"".equals(userInfoFromRedis)) {
            //将值转换为对象后 直接返回出去
            userInfo = JSON.parseObject(userInfoFromRedis,UserInfo.class);
            return userInfo;
        }
        //如果redis中没有这个值 直接调用数据库
        userInfo = userMapper.selUserInfoByUserId(userId);
        return userInfo;
    }

    @Override
    public UserDetailInfoVO getUserDetailInfo(String userId) {
        //登录者用户
        String loginUserId = SimpleUserInfo.getUserId();

        //获取用户信息
        UserInfo userInfo = this.getUserInfo(userId);

        if(userInfo == null) {
            throw new RuntimeException("找不到该id对应的用户");
        }
        //得到该范围的实体类
        UserDetailInfoVO userDetailInfoVO = CommonUtil.copyObject(userInfo, UserDetailInfoVO.class);
        //参数组装
        SingleRelationReqQO singleRelationReqQO = new SingleRelationReqQO();
        singleRelationReqQO.setSenderId(loginUserId);
        singleRelationReqQO.setTargetId(userId);
        //得到请求id
        String reqId = singleRelationReqMapper.getRelationReqIdByBothId(singleRelationReqQO);
        //如果请求id不为空 则status == 1
        if(reqId != null) {
            //说明已经存在 设置成true
            userDetailInfoVO.setExistSingleRelation(true);
            return userDetailInfoVO;
        }
        //不然就是null 则设置成false
        userDetailInfoVO.setExistSingleRelation(false);
        return userDetailInfoVO;
    }

    @Override
    public void updateUserAvatarByUserId(String avatar, String userId) {
        //Date date = DateUtil.localDateTimeToDate(LocalDateTime.now());
        //userMapper.updateUserAvatarByUserId(avatar, userId ,date);
    }

    @Override
    public List<UserInfo> searchUser(UserInfoQO userInfoQO) {
        int current = userInfoQO.getCurrent();
        int size = userInfoQO.getSize();
        userInfoQO.setPageVal(current,size);
        String loginUserId = SimpleUserInfo.getUserId();
        userInfoQO.setLoginUserId(loginUserId);
        //为了索引命中而得到的傀儡userInfo
        List<UserInfo> userInfos = userMapper.searchUser(userInfoQO);

        //遍历设置值
        userInfos.forEach(item ->{
            String userId = item.getId();
            UserInfo userInfoNoSetCatch = this.getUserInfoNoSetCatch(userId);
            //item中只有id、showName与userName
            item.setAvatar(userInfoNoSetCatch.getAvatar());
            item.setSex(userInfoNoSetCatch.getSex());
            item.setSelfComment(userInfoNoSetCatch.getSelfComment());
        });
        return userInfos;
    }
}
